﻿namespace SuperMarieApi.App.Controllers.Framework.DataAccess.SqlBuilder
{
    using System;
    using System.Data;

    using SuperMarieApi.App.Controllers.Framework.Config;
    using SuperMarieApi.App.Controllers.Framework.Entity;

    public class PagingSqlConditionBuilder : SqlConditionBuilder
    {
        int _pageIndex;
        int _pageSize;

        public PagingSqlConditionBuilder(DataCommand dbCommand, PagingQuery pagingInfo, string defaultOrderBy)
            : base(dbCommand, defaultOrderBy,pagingInfo.sort,pagingInfo.order)
        {
            this._pageIndex = pagingInfo.page.HasValue ? pagingInfo.page.Value:ConfigManager.DataAccessConfig.PageIndexStart;
            this._pageSize = pagingInfo.rows.HasValue?pagingInfo.rows.Value:int.MaxValue;
            //如果分页索引从1开始，自动减1
            if (ConfigManager.DataAccessConfig.PageIndexStart == 1)
            {
                this._pageIndex = this._pageIndex - 1;
            }
            //默认分页索引从0开始
            int startRowID = this._pageIndex * this._pageSize + 1;
            int endRowID = (this._pageIndex + 1) * this._pageSize;

            dbCommand.AddParameter("@StartRowID", DbType.Int32, 4, ParameterDirection.Input, startRowID);
            dbCommand.AddParameter("@EndRowID", DbType.Int32, 4, ParameterDirection.Input, endRowID);
            dbCommand.AddOutParameter("@TotalCount", DbType.Int32, 4);
        }

        public int GetTotalCount()
        {
            object totalCount = this._dbCommand.GetParameterValue("@TotalCount");

            return totalCount == null || totalCount == DBNull.Value ? 0 : Convert.ToInt32(totalCount);
        }
    }
}
